<template>
    <div>
        <span style="margin-right: 5px ;font-size: 14px;font-weight: 700 ">角色名称</span>
        <div class="demo-input-suffix"
             style="margin-right: 10px">
            <el-input
                    placeholder="请输入名称"
                    prefix-icon="el-icon-search"
                    size="mini"
                    v-model="input1">
            </el-input>
        </div>
        <span style="margin-right: 5px ;font-size: 14px;font-weight: 700 ">权限字符</span>
        <div class="demo-input-suffix"
             style="margin-right: 10px">
            <el-input
                    placeholder="请输入权限字符"
                    prefix-icon="el-icon-search"
                    size="mini"
                    v-model="input2">
            </el-input>
        </div>



        <span style="margin-right: 5px ;font-size: 14px;font-weight: 700 ">状态</span>
        <div class="demo-input-suffix"
             style="margin-right: 10px ;margin-bottom: 25px">
<!--            <el-input-->
<!--                    placeholder="角色状态"-->
<!--                    prefix-icon="el-icon-search"-->
<!--                    size="mini"-->
<!--                    v-model="input3">-->
<!--            </el-input>-->

            <el-select v-model="input3"
                       size="mini"
                       prefix-icon="el-icon-search"
                       placeholder="角色状态">
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
            </el-select>
        </div>




        <br>
        <div class="block">
            <span class="demonstration" style="margin-right: 5px ;font-size: 14px;font-weight: 700">创建时间</span>
            <el-date-picker
                    size="mini"
                    v-model="value1"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
            </el-date-picker>
        </div>
        <br><br>

        <el-button type="primary" icon="el-icon-search" size="mini" @click="search">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="reset">重置</el-button>
        <br><br>

        <!--  ----------  角色的crud  ----------    -->
        <el-row style="display: inline-block; margin-right: 15px">
            <el-button type="primary" class="el-icon-plus" size="mini" @click="addrole" plain>新增</el-button>
        </el-row>

        <el-row style="display: inline-block; margin-right: 15px">
            <el-button type="success" class="el-icon-edit" size="mini" disabled>修改</el-button>
        </el-row>

        <el-row style="display: inline-block; margin-right: 15px">
            <el-button
                    type="danger"
                    icon="el-icon-delete"
                    @click="delAll"
                    size="mini"
                    :disabled="multipleSelection.length === 0">删除
            </el-button>
        </el-row>


        <el-row style="display: inline-block; margin-right: 15px">
            <el-button
                    type="warning"
                    class="el-icon-download"
                    size="mini"
                    @click="exportuser"
                    :disabled="multipleSelection.length === 0"
                    plain>导出
            </el-button>
        </el-row>


        <br>

        <el-table
                :data="sysRoles"
                style="width: 100%"
                :row-key="getRowKeys"
                @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection"
                    width="55"
                    :selectable="checkSelect"
                    :reserve-selection="true">
            </el-table-column>
            <el-table-column
                    label="角色编号"
                    width="120">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.roleId }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="角色名称"
                    width="120">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.roleName}}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="权限字符"
                    width="120">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.roleKey }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    label="显示顺序"
                    width="120">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.roleSort }}</span>
                </template>
            </el-table-column>


            <el-table-column
                    label="状态"
                    width="120">
                <template slot-scope="scope">
                    <el-switch
                            v-model="scope.row.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-value="0"
                            inactive-value="1"
                            :disabled="scope.row.roleId==1"
                            @change="ChangeStatus(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>

            <el-table-column
                    label="创建时间"
                    width="120">
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.createTime }}</span>
                </template>
            </el-table-column>

            <el-table-column
                    label="操作"
                    width="300">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            icon="el-icon-edit"
                            type="success"
                            v-if="scope.row.roleId!=1"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            icon="el-icon-edit"
                            type="success"
                            v-if="scope.row.roleId==1"
                            @click="handleEdit(scope.$index, scope.row)"
                            disabled>编辑
                    </el-button>

<!--                    <el-button-->
<!--                            size="mini"-->
<!--                            icon="el-icon-circle-check"-->
<!--                            type="primary"-->
<!--                            v-if="scope.row.roleId!=1"-->
<!--                            @click="handleComments(scope.$index, scope.row)">数据权限-->
<!--                    </el-button>-->
<!--                    <el-button-->
<!--                            size="mini"-->
<!--                            icon="el-icon-circle-check"-->
<!--                            type="primary"-->
<!--                            v-if="scope.row.roleId==1"-->
<!--                            @click="handleComments(scope.$index, scope.row)"-->
<!--                            disabled>数据权限-->
<!--                    </el-button>-->

                    <el-button
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            v-if="scope.row.roleId!=1"
                            @click="handleDelete(scope.$index, scope.row)">删除
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            v-if="scope.row.roleId==1"
                            @click="handleDelete(scope.$index, scope.row)" disabled>删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--        添加-->
        <div>
            <!--    添加-->
            <el-dialog title="添加/修改角色"   :visible.sync="dialogFormVisible">
                <el-form :model="sysRole" :rules="rules"  ref="sysRole" >

                    <el-form-item prop="roleName" label="角色名称" style="display: inline-block" :label-width="formLabelWidth">
                        <el-input v-model="sysRole.roleName" style="width: 400px" placeholder="请输入角色名称"
                                  autocomplete="off"></el-input>
                    </el-form-item>

                    <el-form-item prop="roleKey" label="权限字符" style="display: inline-block" :label-width="formLabelWidth">
                        <el-input v-model="sysRole.roleKey" style="width: 400px" placeholder="请输入权限字符"
                                  autocomplete="off"></el-input>
                    </el-form-item>

                    <el-form-item label="角色顺序" style="display: inline-block" :label-width="formLabelWidth">
                        <el-input-number
                                v-model="sysRole.roleSort"
                                style="width: 180px"
                                controls-position="right"
                                @change="handleChange"
                                :min="1" :max="10">
                        </el-input-number>
                    </el-form-item>
                    <br>

                    <el-form-item label="状态" :label-width="formLabelWidth">
                        <el-radio v-model="sysRole.status" label="0">正常</el-radio>
                        <el-radio v-model="sysRole.status" label="1">停用</el-radio>
                    </el-form-item>

                    <el-form-item label="菜单权限" :label-width="formLabelWidth">
                        <el-checkbox v-model="isSelectAll" @change="selectAll($event,'trees')">展开/折叠</el-checkbox>
                        <el-checkbox v-model="menuNodeAll" @change="treeNodeAll($event,'trees')">全选/全不选</el-checkbox>
<!--                        <el-checkbox v-model="folding3" >父子联动</el-checkbox>-->
                        <br>
                        <el-tree
                                style="border: 1px solid lightgray;width: 400px"
                                :data="menus"
                                show-checkbox
                                default-expand-all
                                node-key="menuId"
                                ref="trees"
                                highlight-current
                                :default-expand-all="isExpand"
                                :props="defaultProps">
                        </el-tree>
                    </el-form-item>

                    <el-form-item prop="remark" label="备注" :label-width="formLabelWidth">
                        <el-input type="textarea" v-model="sysRole.remark" placeholder="请输入内容" style="width: 480px"
                                  autocomplete="off"></el-input>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveRole()">确 定</el-button>
                </div>
            </el-dialog>
        </div>

        <!--        //分页-->
        <el-pagination
                background
                :page-size="pageSize"
                layout="prev, pager, next"
                @current-change="loadRoles"
                :total="total">
        </el-pagination>


        <el-button
                plain
                @click="open1"
                style="display: none">
            删除成功
        </el-button>
        <el-button
                plain
                @click="open2"
                style="display: none">
            添加成功
        </el-button>
        <el-button
                plain
                @click="open3"
                style="display: none">
            修改成功
        </el-button>
        <el-button
                plain
                @click="open4"
                style="display: none">
            添加失败
        </el-button>
        <el-button
                plain
                @click="open5"
                style="display: none">
            导出成功
        </el-button>

    </div>
</template>

<script>
    export default {
        name: "Role",
        data() {
            return {
                rules:{
                    roleName:[
                        { required: true, message: '请输入角色名称', trigger: 'blur' },
                    ],
                    roleKey:[
                        { required: true, message: '请输入权限字符', trigger: 'blur' },
                    ],
                    remark:[
                        { required: true, message: '请输入备注', trigger: 'blur' },
                    ]
                },
                menuNodeAll:false,
                isSelectAll: false,
                isExpand:false,
                menus:[],
                defaultProps: {
                    children: 'menus',
                    label: 'menuName'
                },
                multipleSelection: [],
                input: true,
                input1: '',
                input2: '',
                input3: '',
                total: 0,//人员总数
                current: 1,//当前页数
                pageSize: 3,
                formLabelWidth: "120px",
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }]
                },
                value1: '',
                sysRole: {
                    roleId: "",
                    roleName: "",//角色名称
                    roleKey: "",//权限字符
                    roleSort: "",//显示顺序
                    status: "0",//状态
                    createTime: "",
                    remark: "" ,//备注
                    menuIds:[],
                    createBy: '',
                    updateBy:''
                },
                sysRoles: [],
                dialogFormVisible: false,
            }

        },

        methods: {

            open1() {
                this.$notify({
                    title: '删除成功',
                    message: '',
                    type: 'success'
                });
            },

            open2() {
                this.$notify({
                    title: '添加成功',
                    message: '',
                    type: 'success'
                });
            },

            open3() {
                this.$notify({
                    title: '修改成功',
                    message: '',
                    type: 'success'
                });
            },

            open4() {
                this.$notify.error({
                    title: '添加失败',
                    message: ''
                });
            },

            open5() {
                this.$notify({
                    title: '导出成功',
                    message: '',
                    type: 'success'
                });
            },

            checkSelect (row) {
                let isChecked = true;
                if (row.roleId==1) { // 判断里面是否存在某个参数
                    isChecked = false
                } else {
                    isChecked = true
                }
                return isChecked
            },
            // 折叠、展开
            selectAll(value,type) {

                if (type === "trees") {
                    let treeList = this.menus;
                    for (let i = 0 ; i < treeList.length ; i++){
                        this.$refs.trees.store.nodesMap[treeList[i].menuId].expanded = value;
                    }
                }
            },
            //全选
            treeNodeAll(value,type){
                if (type === "trees") {
                    this.$nextTick(()=>{
                        this.$refs.trees.setCheckedNodes(value?this.menus : []);
                    })
                }
            }

            ,
            //添加弹窗
            addrole() {
                this.$nextTick(()=>{
                    this.$refs.trees.setCheckedKeys([]);
                }),
                this.sysRole={
                    roleId: "",
                        roleName: "",//角色名称
                        roleKey: "",//权限字符
                        roleSort: "",//显示顺序
                        status: "0",//状态
                        createTime: "",
                        remark: "" ,//备注
                        menuIds:[]
                },
                this.dialogFormVisible = true;
            },
            // handleChange(value) {
            //     console.log(value);
            // },
            // 添加角色
            saveRole() {
                this.sysRole;
                if (this.sysRole.roleId == null || this.sysRole.roleId==''){
                    this.sysRole.createBy= localStorage.getItem("username");
                    this.axios.post("http://localhost:8080/roles/addroles", this.sysRole)
                        .then(res => {
                            if ( res.data.data=="添加失败"){
                                this.open4();
                            }else {
                                this.getMenu();
                                this.axios.post("http://localhost:8080/roles/addrolesmenus?roleId="+res.data.data, this.sysRole)
                                    .then(res=>{
                                        this.open2();
                                        this.loadRoles(this.current);
                                    })
                            }
                        })
                }else {
                    this.getMenu();
                    this.sysRole.updateBy= localStorage.getItem("username");
                    this.axios.post("http://localhost:8080/roles/updateroles", this.sysRole)
                            .then(res => {
                                this.axios.post("http://localhost:8080/roles/updaterolesmenu",res.data.data)
                                    .then(res => {
                                        if (res.data.data == "修改成功"){
                                            this.open3();
                                            this.loadRoles(this.current);
                                        }
                                    })
                        })

                }
                this.dialogFormVisible = false;
                this.loadRoles(this.current);
            },
            // 获取树的值
            getMenu(){
                let checkedKeys=this.$refs.trees.getCheckedKeys();
                let halfCheckedKeys=this.$refs.trees.getHalfCheckedKeys()
                checkedKeys.unshift.apply(checkedKeys,halfCheckedKeys);
                this.sysRole.menuIds=checkedKeys;
                console.log(this.sysRole.menuIds);
            },
            //修改状态
            ChangeStatus(row) {
                // alert("id为："+row.roleId+"，当前status为："+row.status);
                this.axios.put("http://localhost:8080/roles/status", row)
                    .then(res => {
                        if (res.data.data == "修改状态成功") {
                            this.open3();
                            this.loadRoles(this.current);
                        }
                    })
            },
            //重置按钮
            reset() {
                this.input1 = '',
                    this.input2 = '',
                    this.input3 = '',
                    this.value1 = ['', ''],
                    this.current = 1,
                    this.total = 1,
                    this.search(this.current)
            },
            //全选单选框
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //显示数据表
            loadRoles(current) {
                this.current = current;
                this.sysRole.roleId = 0;
                this.sysRole.roleSort = 0;
                this.axios.post("http://localhost:8080/roles/text?current=" + this.current, {
                    "roleName": this.input1,
                    "roleKey": this.input2,
                    "status": this.input3,
                    "createTime": this.value1[0],
                    "updateTime": this.value1[1]
                })
                    .then(res => {
                        console.log(res);
                        this.sysRoles = res.data.data.records;
                        this.current = res.data.data.current;
                        this.total = res.data.data.total;
                        // if (this.input1!=null || this.input2!=null || this.input3!=null ){
                        //     this.sysRoles=res.data.data;
                        // }
                    })
            },
            //导出excel
            exportuser() {

                this.axios({
                    method: "post",
                    url: "http://localhost:8080/roles/export", // 请求地址
                    data: this.multipleSelection, // 参数
                    responseType: 'blob' // 表明返回服务器返回的数据类型
                }).then(
                    res => {
                        if (res && res.data) {
                            this.open5();
                            // 调用js-file-download下载文件，第一个参数是数据流，第二个参数是文件名，我这后端返回时把文件名放到响应的header的filename字段中，所以用这种方式取出
                            this.jsFileDownload(res.data, decodeURIComponent("用户信息.xlsx"))
                        }
                    }
                )
            },
            handleSelectionChange(val) {
                console.log(val)  //打印选中的行集合
                this.multipleSelection = val;
            },
            //点击行触发，选中或不选中复选框
            handleRowClick(row, column, event) {
                this.$refs.handSelectTest_multipleTable.toggleRowSelection(row);
                console.log(row)  //打印的时当前选中的行
            },
            //菜单列表
            loadMenus(){
                this.axios.get("http://localhost:8080/getMenus")
                    .then(res => {
                        this.menus=res.data.data;
                        console.log(11);
                    })
            },
            //模糊查询
            search(current) {
                // this.loadRoles(current);
                this.current=1;
                this.loadRoles(this.current);
            },

            //回显
            handleEdit(index, row) {
                console.log(index, row);
                this.sysRole = JSON.parse(JSON.stringify(row));
                this.dialogFormVisible = true;
                this.axios.get("http://localhost:8080/roles/getbyroleId/"+this.sysRole.roleId)
                    .then(res => {
                        this.$nextTick(()=>{
                            this.$refs.trees.setCheckedKeys(res.data.data.menuIds);
                        })
                    })
            },
            //删除
            handleDelete(index, row) {
                if (confirm("是否确定？")) {
                    this.axios.delete("http://localhost:8080/roles/del/" + row.roleId)
                        .then(res => {
                            if (res.data.data == "删除成功") {
                                this.open1();
                                this.current=1;
                                this.loadRoles(this.current);
                                this.reset();
                            }
                        })
                }
            },
            //多选删除
            delAll() {
                if (confirm("是否确定？")) {
                    for (var i = 0; i < this.multipleSelection.length; i++) {

                        this.axios.delete("http://localhost:8080/roles/del/" + this.multipleSelection[i].roleId)
                            .then(res => {
                                this.current=1;
                                this.loadRoles(this.current);
                                this.reset();
                            })
                    }
                    this.open1();
                }
                this.reset();
            },
            getRowKeys(row){
                return row.roleId;
            },
        },
        created() {
            this.loadRoles(this.current);
            this.loadMenus();
        }
    }
</script>

<style scoped>
    .demo-input-suffix {
        display: inline-block;
        width: 150px;
    }

    .block {
        display: inline-block;
    }

    /deep/ .el-table th > .cell {
        text-align: center;
    }

    /deep/ .el-table .cell {
        text-align: center;
    }

</style>